import React, { useEffect, useState } from 'react';
import { Form, Input, Select, Switch, Button, Space, Card, Typography, Tag, Collapse } from 'antd';
import { Function, FunctionFormValues, FunctionType, FunctionStatus } from './store/functionTypes';

const { TextArea } = Input;
const { Title } = Typography;
const { Panel } = Collapse;

interface FunctionFormProps {
  initialValues?: Function;
  type?: 'create' | 'edit' | 'view';
  onSubmit: (values: FunctionFormValues) => void;
  onCancel: () => void;
}

const FunctionForm: React.FC<FunctionFormProps> = ({ initialValues, type, onSubmit, onCancel }) => {
  const [form] = Form.useForm();
  useEffect(() => {
    form.resetFields();
  }, [initialValues, form]); 

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      // 将中文的状态和类型转换回英文
      const processedValues = {
        ...values,
      };
      // 验证JSON格式
      try {
        JSON.parse(processedValues.definition);
      } catch (error) {
        form.setFields([{ name: 'definition', errors: ['请输入有效的JSON格式'] }]);
        return;
      }
      onSubmit(processedValues);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const isViewMode = type === 'view';
  return (
    <Form
      form={form}
      layout="vertical"
      disabled={isViewMode}
      initialValues={{
        ...initialValues,
      }}
      onFinish={handleSubmit}
    >
      {/* 基本信息卡片 */}
      <Card title="基本信息" style={{ marginBottom: 16 }}>
        <Form.Item
          name="name"
          label="函数名称"
          rules={[
            { required: true, message: '请输入函数名称' },
            { max: 50, message: '函数名称不能超过50个字符' }
          ]}
        >
          <Input placeholder="请输入函数名称" />
        </Form.Item>

        <Form.Item
          name="frontendAction"
          label="函数标识"
          rules={[
            { required: true, message: '请输入函数标识' },
            { pattern: /^[a-zA-Z0-9_]+$/, message: '只能输入英文、数字和下划线' },
            { max: 30, message: '函数标识不能超过30个字符' }
          ]}
        >
          <Input placeholder="请输入函数标识" />
        </Form.Item>

        <Form.Item
          name="type"
          label="函数类型"
          rules={[{ required: true, message: '请选择函数类型' }]}
        >
          <Select placeholder="请选择函数类型">
            <Select.Option value="system">系统函数</Select.Option>
            <Select.Option value="direct">前端函数</Select.Option>
            <Select.Option value="plugin">插件函数</Select.Option>
            <Select.Option value="custom">自定义函数</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="description"
          label="函数描述"
          rules={[{ max: 500, message: '描述不能超过500个字符' }]}
        >
          <TextArea rows={4} placeholder="请输入函数描述" />
        </Form.Item>

        <Form.Item
          name="version"
          label="版本号"
          rules={[
            { required: true, message: '请输入版本号' },
            { pattern: /^[0-9]+\.[0-9]+\.[0-9]+$/, message: '版本号格式不正确，如：1.0.0' }
          ]}
        >
          <Input placeholder="请输入版本号" />
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          rules={[{ required: true, message: '请选择状态' }]}
        >
          <Select placeholder="请选择状态">
            <Select.Option value='0'>草稿</Select.Option>
            <Select.Option value='1'>已发布</Select.Option>
            <Select.Option value='2'>已弃用</Select.Option>
            <Select.Option value='3'>已归档</Select.Option>
          </Select>
        </Form.Item>
      </Card>

      {/* 函数定义卡片 */}
      <Card title="函数定义" style={{ marginBottom: 16 }}>
        <Form.Item
          name="definition"
          label="函数定义（JSON格式）"
          rules={[
            { required: true, message: '请输入函数定义' },
            { max: 10000, message: '函数定义不能超过10000个字符' }
          ]}
          extra={
            <div>
              <p>函数定义示例：</p>
              <pre>
                {`{
                    "name": "get_weather",
                    "description": "获取指定城市的天气信息",
                    "parameters": {
                      "type": "object",
                      "properties": {
                        "city": {
                          "type": "string",
                          "description": "城市名称"
                        },
                        "unit": {
                          "type": "string",
                          "enum": ["celsius", "fahrenheit"],
                          "description": "温度单位"
                        }
                      },
                      "required": ["city"]
                    }
                  }`}
              </pre>
            </div>
          }
        >
          <TextArea rows={10} placeholder="请输入函数定义（JSON格式）" />
        </Form.Item>
      </Card>

      {/* 高级设置卡片 - 改为折叠面板 */}
      <Collapse style={{ marginBottom: 16 }}>
        <Panel header="高级设置" key="advanced">
          <Form.Item
            name="tags"
            label="标签"
          >
            <Select
              mode="tags"
              style={{ width: '100%' }}
              placeholder="请输入标签"
            />
          </Form.Item>

          <Form.Item
            name="modelIds"
            label="适用的模型"
          >
            <Select
              mode="multiple"
              style={{ width: '100%' }}
              placeholder="请选择适用的模型"
            />
          </Form.Item>

          <Form.Item
            name="isPublic"
            label="是否公开"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="isEnabled"
            label="是否启用"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="rateLimit"
            label="速率限制（次/分钟）"
            rules={[
              { type: 'number', min: 1, message: '速率限制必须大于0' }
            ]}
          >
            <Input type="number" min={1} />
          </Form.Item>

          <Form.Item
            name="timeout"
            label="超时时间（毫秒）"
            rules={[
              { type: 'number', min: 1000, message: '超时时间必须大于1000毫秒' }
            ]}
          >
            <Input type="number" min={1000} step={1000} />
          </Form.Item>

          <Form.Item
            name="retryTimes"
            label="重试次数"
            rules={[
              { type: 'number', min: 0, max: 5, message: '重试次数必须在0到5之间' }
            ]}
          >
            <Input type="number" min={0} max={5} />
          </Form.Item>

          <Form.Item
            name="retryInterval"
            label="重试间隔（毫秒）"
            rules={[
              { type: 'number', min: 1000, message: '重试间隔必须大于1000毫秒' }
            ]}
          >
            <Input type="number" min={1000} step={1000} />
          </Form.Item>

          <Form.Item
            name="proxy"
            label="代理地址"
            rules={[
              { type: 'url', message: '请输入有效的URL地址' }
            ]}
          >
            <Input placeholder="请输入代理地址" />
          </Form.Item>
        </Panel>
      </Collapse>

      {/* 表单按钮 */}
      <Form.Item>
        <Space>
          <Button type="primary" htmlType="submit">
            保存
          </Button>
          <Button onClick={onCancel}>
            取消
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default FunctionForm;